#include "uart.hpp"
#include <iostream>

void data_received_callback(const std::vector<uint8_t> &data) 
{
	static unsigned int i = 0;
	std::cout<< "\r uart receive data ! rollingcounter " << i;
	std::fflush(stdout);
	i++;
}


void do_serial(const std::string &port_name, int baud_rate, bool ctsrts) 
{
	try {
		uart ut(port_name, baud_rate, ctsrts);
		ut.set_data_callback(data_received_callback); 
		ut.open_port();

#if 0
		while(1){
			std::this_thread::sleep_for(std::chrono::seconds(300));
		}
#endif		
	} catch (const std::exception &e) {
		std::cerr << "Exception: " << e.what() << std::endl;
	}
}


int main(int argc, char *argv[]) 
{
	if (argc < 2) {
		std::cerr << "Usage: " << argv[0] << " <port_name> [baud_rate] [ctsrts]" << std::endl;
		return 1;
	}

	std::string port_name = argv[1];
	int baud_rate = B115200;
	bool ctsrts = false;

	if (argc >= 3) {
		int baud = std::stoi(argv[2]);
		switch (baud) {
			case 9600:		
				baud_rate = B9600;
			break;
			case 19200:
				baud_rate = B19200;
			break;
			case 38400:
				baud_rate = B38400;
			break;
			case 57600:
				baud_rate = B57600;
			break;
			case 115200:
				baud_rate = B115200;
			break;
			default:
				std::cerr << "Unsupported baud rate. Using default 115200." << std::endl;
			break;
		}
	}

		if (argc >= 4) {
			ctsrts = std::stoi(argv[3]) != 0;
		}
		
		std::cout << "*******************" << std::endl;
		std::cout << "Portname:" << port_name << std::endl;
		std::cout << "Baudrate:" << std::stoi(argv[2]) << std::endl;
		std::cout << "Ctsrts:"   << ctsrts    << std::endl;
		std::cout << "*******************" << std::endl;
		
		do_serial(port_name, baud_rate, ctsrts);
		return 0;
}




